/* Copyright 2014 Jan Wolter */

#include "stack.h"
#include "game.h"

char *gamename= "Simple Pairs";
char *gameopt= "";
Stack *gathered= NULL;

void printBlockTen(FILE *f);

int nplayed= 0;
int nwon= 0;
int cardsleft= 0;

#define MAXTAB 52
Card *tableau[MAXTAB];
#define NTAB  9
int ntab;
extern int n_opt;

Stack *dck;

void setopt(char c) {}

/* This is the main program for setting up the current game */
void exec(int gather, int arif, int over, int cut)
{
    int i;
    ntab= (n_opt > 0) ? n_opt : NTAB;

    /* Could set things like ndeck, nsuit here */

    /* Build and shuffle the deck */
    dck= mixcards(arif, over, cut);
    int left= dck->n;

    /* Create the tableau */
    for (i= 0; i < ntab; i++)
	tableau[i]= popStack(dck);

    if (verbose > 2) printBlockTen(stdout);

    while (left > 0)
    {
	/* Find a pair i,j to remove */
	int i, j; 
	for (i= 0; i < ntab - 1; i++)
	{
	    if (tableau[i] == NULL) continue;

	    for (j= i+1; j < ntab; j++)
	    {
		if (tableau[j] == NULL) continue;
		if (tableau[i]->n == tableau[j]->n)
		    goto done;
	    }
	}
	done:;

	if (i < ntab - 1 && j < ntab)
	{
	    /* Found a pair to remove */
	    if (verbose > 2)
		printf("Remove %d (%c) and %d (%c)\n",
		    i+1, rankletter[tableau[i]->n],
		    j+1, rankletter[tableau[j]->n]);

	    left-= 2;

	    tableau[j]= popStack(dck);
	    tableau[i]= popStack(dck);
	}
	else
	    break;

	if (verbose > 3) printBlockTen(stdout);
    }

    int win= (left == 0);

    nplayed++;
    cardsleft+= left;
    if (win) nwon++;

    if (verbose > 0) printf("Left=%d\n", left);

    freeStack(dck);
}

/* Not implemented (yet?) */
void gatherAll()
{
}

void printBlockTen(FILE *f)
{
    printf("Tableau:");
    for (int i= 0; i < ntab; i++)
    {
	fputc(' ',f);
	if (tableau[i] == NULL)
	    fputc('_',f);
	else
	    fputc(rankletter[tableau[i]->n],f);
    }
    fputc('\n',f);
    printStack(f, "Deck", dck);
}

void summary()
{
    printf("Played:     %d games\n",nplayed);
    printf("Won:        %d games (%.2f%)\n",nwon,(float)nwon*100/nplayed);
    printf("Cards Left: %.2f\n",(float)cardsleft/nplayed);
}
